package com.lilingguo.easyserver.config;

import com.lilingguo.easyserver.core.EasyServer;
import com.lilingguo.easyserver.pojo.ServiceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * EasyServer核心配置类
 *
 * @Author: 黎铃果
 * @Date: 2020/5/28 16:21
 */
@Configuration
@ComponentScan("com.lilingguo.easyserver")
public class EasyServerConfigure {

    /**
     * 服务名，默认值：easyserver-client
     */
    @Value("${spring.application.name:easyserver-client}")
    private String name;

    /**
     * 端口
     */
    @Value("${server.port}")
    private int port;

    @Autowired
    private ClientProperties clientProperties;
    @Autowired
    private ServerProperties serverProperties;

    /**
     * 本地服务信息
     */
    @Bean
    @ConditionalOnMissingBean
    public ServiceInfo serviceInfo() {
        // get registerUrl
        String registerUrl = "http://" + serverProperties.getAddress() + "/easyserver";
        // get ip
        String ip = clientProperties.getIp();
        if (ip == null) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                ip = "localhost";
            }
        }
        ServiceInfo info = new ServiceInfo();
        info.setName(name);
        info.setIp(ip);
        info.setPort(port);
        info.setRegisterUrl(registerUrl);
        info.setMaximalLife(clientProperties.getHealthTtl());
        return info;
    }

    /**
     * RestTemplate
     */
    @Bean
    @ConditionalOnMissingBean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * EasyServer核心类
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({RestTemplate.class, ServiceInfo.class})
    public EasyServer easyServer(RestTemplate restTemplate, ServiceInfo info) {
        return new EasyServer(restTemplate, info);
    }

}
